const App = {
    mixins: [Save],//配置文件，路径/utils/mixins.js
    data() {
        return {
            originalTableData2: [],
            selectedCount: 0,

            checkboxOptions2: [],
            // 复选框选项数组
            checkboxOptions: [],
            // 选中的选项值数组
            selectedOptions: [],

            Task_SerialNumber: "",
            team_SerialNumber: "",
            tableData: [],
            dialogFormVisible: false,
        };
    },
    mounted() {
        let ls_URL = window.location.href;
        this.team_SerialNumber = getQueryObject(ls_URL, "team_SerialNumber");
        this.Task_SerialNumber = getQueryObject(ls_URL, "Task_SerialNumber");

        this.Getplan_memberAndSetData(this.team_SerialNumber);
    },
    methods: {
        xin() {
            this.dialogFormVisible = true;
        },

        Getplan_memberAndSetData(Arg2) {
            const _this = this;
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/generalBusiness/generalQueryBySQLSerialNumber`,
                method: "post",
                data: {
                    SQLSerialNumber: "SQL_patrol_member_list", //sql名
                    Condition: "", //不必选的条件
                    ExtensionCondition: window.btoa(
                        unescape(
                            encodeURIComponent(
                                " where patrol_member.Row_Status='0' and  patrol_member.team_SerialNumber='" + Arg2 + "'"
                            ))),
                },
                success: (res) => {
                    console.log(res);

                    _this.checkboxOptions = res;;
                    // _this.cren(Arg1);
                },
                complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest);
                },
            });
        },

        cren(Arg_res) {
            const _this = this;
            //为人员列表赋值

            ;


        },

        // 设置复选框选中状态的方法
        setCheckboxesSelected(selectedMembers) {
            console.log(
                "设置复选框选中状态，已选中成员数量:",
                selectedMembers.length
            );

            const selectedIds = selectedMembers.map(
                (member) => member.ID_Card_Number
            );
            // const captainId = this.childDataForm[0]?.ID_Card_Number;
            const selectedIdMap = new Map(selectedIds.map(id => [id, true]));

            this.checkboxOptions.forEach(option => {
                // if (option.ID_Card_Number === captainId) {
                //   option.checked = false;
                //   return;
                // }

                const isSelected = selectedIdMap.has(option.ID_Card_Number);
                option.checked = isSelected;
                console.log(`成员 ${option.Personal_Name} 选中状态:`, isSelected);
            });



            this.updateSelectedCount();
            this.handleCheckboxChange();
            console.log("设置完成，当前已选数量:", this.selectedCount);
        },

        handleCheckboxChange(option) {

            let _this = this;
            const selectedMembers = _this.checkboxOptions.filter(
                (option) =>
                    option.checked
            );
            console.log("watch1", this.tableData)

            this.tableData = selectedMembers.map((option) => {


                //​覆盖策略​：默认行为（无需额外处理）
                return {

                    Contact_Phone: option.Contact_phone || "", // 确保使用option对象优先使用 original.Mobile，若不存在则回退到 option.Contact_Phone，最后保底为空字符串

                    Personal_Name: option?.Personal_Name || "",
                    ID_Card_Number: option?.ID_Card_Number || ""

                };
            });
            console.log("watch2", this.tableData)

            this.updateSelectedCount();
        },

        // 清空选中并移除选项
        clearAll() {

            // 没有负责人时，清空列表
            this.checkboxOptions = [];


            // 更新已选数量
            this.updateSelectedCount();
        },
        // 更新已选数量
        updateSelectedCount() {
            this.selectedCount = this.checkboxOptions.filter(
                (option) => option.checked
            ).length;
        },
        async handleSubmit1() {
            const allValid = await this.validateAllForms();
            if (allValid) {
                this.dataForm.Task_SerialNumber = this.Task_SerialNumber;
                this.loading = true;
                let ls_URL = window.location.href;
                const action = getQueryObject(ls_URL, "action");   // 获取 action 参数
                let lJSONObject_Data_Options = new Object();
                lJSONObject_Data_Options = JSON.parse(document.getElementById("MainTable").getAttribute("data-options"));

                let ls_MainTableName = lJSONObject_Data_Options.TableName;
                let ls_DataForm = lJSONObject_Data_Options.form;
                let ls_primary_key = lJSONObject_Data_Options.primary_key;
                //没有子表下面内容就会报错，try/catch抛出异常
                try {
                    //可能涉及多个子表
                    document.getElementById("ChildTable").querySelectorAll(".el-descriptions").forEach(item => {
                        if (item.hasAttribute('data-options')) {
                            let lJSONObject_ChildData_Options = new Object();
                            lJSONObject_ChildData_Options = JSON.parse(item.getAttribute("data-options"));

                            let ls_ChildTableName = lJSONObject_ChildData_Options.TableName;
                            let ls_ChildDataForm = lJSONObject_ChildData_Options.form;
                            // let ls_ParentTableName = lJSONObject_ChildData_Options.ParentTableName;
                            if (this[ls_DataForm][ls_primary_key]) {
                                this[ls_ChildDataForm].forEach(item => {
                                    item[ls_primary_key] = this[ls_DataForm][ls_primary_key];
                                })
                            }
                            //建立子表结构体
                            let JSONArray_ChildRecord = new Array();
                            JSONArray_ChildRecord = this[ls_ChildDataForm];
                            if (!this[ls_DataForm].Children) {
                                this[ls_DataForm].Children = new Object();
                            }
                            this[ls_DataForm].Children[ls_ChildTableName] = JSONArray_ChildRecord;
                        }
                    })
                } catch (error) {

                }
                //建立新增提交结构
                let lJSONObject_DataSet = new Object();
                if (action == 'Add') {
                    if (this.nodeKey) {
                        this[ls_DataForm].Parent_SerialNumber = this.nodeKey;
                    }
                    let lJSONArray_Record = new Array();
                    lJSONArray_Record.push(this[ls_DataForm]);
                    let lJSONObject_Table = new Object();
                    lJSONObject_Table[ls_MainTableName] = lJSONArray_Record;
                    lJSONObject_DataSet[action] = lJSONObject_Table;
                } else if (action == 'Modify') {
                    const { add, modify } = this.deal(this[ls_DataForm]);
                    let lJSONArray_Record = new Array();
                    lJSONArray_Record.push(modify);

                    let lJSONObject_Table = new Object();
                    lJSONObject_Table[ls_MainTableName] = lJSONArray_Record;

                    lJSONObject_DataSet[action] = lJSONObject_Table;
                    lJSONObject_DataSet['Add'] = new Object();
                    if (add != null) {
                        let lJSONArray_Record_Add = new Array();
                        lJSONArray_Record_Add.push(add);

                        let lJSONObject_Table_Add = new Object();
                        lJSONObject_Table_Add[ls_MainTableName] = lJSONArray_Record_Add;

                        lJSONObject_DataSet['Add'] = lJSONObject_Table_Add;
                    }
                }
                let Operation_Main = JSON.stringify(deepClone(lJSONObject_DataSet));
                lJSONObject_DataSet['Add']['base_operation_log'] = [{
                    Operation_Type: '0',
                    Operation_Path: this.relativePath,
                    Operation_Main,
                    Operation_Interface: "generalSaveByRequestBody",
                    Operation_IP: getIpAddress()
                }]
                console.log(lJSONObject_DataSet);

                submitSave(lJSONObject_DataSet, (res) => {
                    if (res.Status == 'success') {

                        window.location.href = "./index_taskPlan.html?action=Query&nodeKey=" + this.Task_SerialNumber+"&team_SerialNumber="+ this.team_SerialNumber;

                    }
                    this.loading = false;
                })

            } else {
                this.$message({
                    message: '存在未填写的必填项！',
                    type: 'warning'
                });
            }
        },
    },

};
const { createApp, ref } = Vue;
const app = createApp(App);
app.use(ElementPlus, { locale: zhCn });
//这种方式是引入全部图标，无需单个引入
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
    app.component(key, component);
}
app.component('yl-upload', ylUpload);
app.component('yl-select', ylSelect);
app.component('yl-text-editor', ylTextEditor);
const ElMessage = ElementPlus.ElMessage;
app.mount("#app");
